package com.walker.util;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
//import org.junit.After;
//import org.junit.Before;
//import org.junit.Test;
import org.springframework.stereotype.Repository;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Repository
public class ESUtils {
	public RestHighLevelClient client;

	public RestHighLevelClient initSession(String host, int port, String user, String passwd) {
		try {
			final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, passwd));

			RestClientBuilder builder = RestClient.builder(new HttpHost(host, port))
					.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
						@Override
						public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
							return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
						}
					});

			this.client = new RestHighLevelClient(builder);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return this.client;
	}

	public void initSession(String url) {
		client = new RestHighLevelClient(RestClient.builder(HttpHost.create(url)));
	}

	public void close() throws IOException {
		client.close();
	}

	// @Test //创建索引库
	public void testCreateHotelIndex() throws IOException {
		// 1.创建Request对象
		CreateIndexRequest request = new CreateIndexRequest("muluzc");
		// 2.请求参数 source：创建索引库的DSL语句，xContentType：数据类型
		// request.source(HotelConstants.MAPPING_TEMPLATE,XContentType.JSON);
		// 3.发送请求,创建索引库
		client.indices().create(request, RequestOptions.DEFAULT);
	}

	// @Test
	public void allIndex() {
		ClusterHealthRequest request = new ClusterHealthRequest();
		try {
			ClusterHealthResponse responese = client.cluster().health(request, RequestOptions.DEFAULT);
			Set<String> indices = responese.getIndices().keySet();
			for (String str : indices) {
				System.out.println(str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	// @Test
	public List<Object> getIndexDocument(String index, int size) throws Exception {
		List<Object> rowList = new ArrayList<>();
		SearchRequest request = new SearchRequest(index);
		request.source().size(size);
		try {
			SearchResponse response = client.search(request, RequestOptions.DEFAULT);
			Object document = Configuration.defaultConfiguration().jsonProvider().parse(String.valueOf(response));
			Object properties = JsonPath.read(document, "$.hits.hits");

			if (properties instanceof ArrayList<?>) {
				for (Object o : (List<?>) properties) {
					if (o instanceof Map) {
						Object _source = ((Map) o).get("_source");
						rowList.add(_source);
					}
				}
			}
			// rowList.forEach(System.err::println);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		} finally {
			close();
		}
		return rowList;
	}

	// @Test
	public void getIndexDocument() throws Exception {
		System.out.println(AesEncryptUtils.decrypt("bVNp8GLkh0NvuYQstuUXC3fclwMqGdfdEYf/NsyKjsE="));
		// getIndexDocument("http://172.30.132.191:29200", "elastic",
		// "o4DUrtqarWqZg289XHYG", "datajobindex_v2", 10);
		getIndexDocument("http://172.30.132.191:29200", "elastic", "o4DUrtqarWqZg289XHYG", "datahubretentionindex_v2",10);
	}

	@SuppressWarnings({ "rawtypes", "unchecked", "restriction" })
	public List<Map<String, Object>> getIndexDocument(String url, String user, String passwd, String index, int size)
			throws Exception {
		List<Map<String, Object>> rowList = new ArrayList<>();
		url = url + "/" + index + "/_search?size=" + size;
		String auth = "";
		if (!CommonUtils.isNull(user)) {
			auth = "Basic " + new sun.misc.BASE64Encoder().encode((user + ":" + passwd).getBytes());
		}

		String indexData = RestTemplateUtil.okGet(url, auth);
		Object properties = JsonPath.read(String.valueOf(indexData), "$.hits.hits");
		if (properties instanceof ArrayList<?>) {
			for (Object o : (List<?>) properties) {
				if (o instanceof Map) {
					Map _source = (Map) ((Map) o).get("_source");
					Object type = ((Map) o).get("_type");
					if (_source instanceof Map) {
						((Map) _source).put("type", type);
						rowList.add(_source);
					}
				}
			}
		}
		rowList.forEach(action -> System.out.println(action));
		return rowList;
	}
}